package com.jeesite.modules.pay.totalPay.restController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.responseReturn.utils.UUID;
import com.jeesite.modules.jdProduct.entity.DelayOrder;
import com.jeesite.modules.jdProduct.service.DelayOrderService;
import com.jeesite.modules.pay.totalPay.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.CacheUtils;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.ZtColor;
import com.jeesite.modules.goods.entity.ZtFinancial;
import com.jeesite.modules.goods.entity.ZtGoods;
import com.jeesite.modules.goods.entity.ZtGoodsOrder;
import com.jeesite.modules.goods.entity.ZtOrder;
import com.jeesite.modules.goods.entity.ZtSpecifications;
import com.jeesite.modules.goods.entity.ZtTrolley;
import com.jeesite.modules.goods.service.ZtAddrService;
import com.jeesite.modules.goods.service.ZtColorService;
import com.jeesite.modules.goods.service.ZtFinancialService;
import com.jeesite.modules.goods.service.ZtGoodsOrderService;
import com.jeesite.modules.goods.service.ZtGoodsService;
import com.jeesite.modules.goods.service.ZtJDorderService;
import com.jeesite.modules.goods.service.ZtOrderService;
import com.jeesite.modules.goods.service.ZtQuanService;
import com.jeesite.modules.goods.service.ZtQuanselfService;
import com.jeesite.modules.goods.service.ZtSpecificationsService;
import com.jeesite.modules.goods.service.ZtTrolleyService;
import com.jeesite.modules.pay.totalPay.service.NativePayService;
import com.jeesite.modules.pay.totalPay.util.HttpXmlUtils;
import com.jeesite.modules.pay.totalPay.util.WxSignUtils;
import com.jeesite.modules.pay.wxpay.api.ConstantUtil;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;

/**
 * 
 * @author tz
 * @category 支付入口 controller <br>
 * @version 1.0 <br>
 * 
 *          2017-9-13 19:58:35<br>
 *          nativePay为目前两种支付的入口，其他参数可反编译jar 重新抒写加入<br>
 * 
 * 
 * 
 *          原生支付：http://localhost:8888/interface/native/nativePay/1||2
 *          H5支付：http://localhost:8888/tz/H5
 * 
 * 
 *          微信H5支付的时候获取ip地址是客户端的ip地址，后面唤起微信支付的也是需要与客户端的ip地址对应，不然会出现，具体看官网文档。
 *          其次微信H5支付的成功返回页面在得到支付请求时的地址后追加URL编码，具体看官网文档。
 */

@Controller
@RequestMapping(value = "${frontPath}/interface/native")
public class NativePayController extends BaseController {

	protected static Logger logger = LoggerFactory
			.getLogger(NativePayController.class);

	private String pay_title = "企购购商城";
	private String orderNo = "";// 订单号delayOrderService

	private String openid;
	@Autowired
	ZtQuanselfService ztQuanselfService;
	@Autowired
	ZtFinancialService ztFinancialService;

	@Autowired
	private ZtAdminService ztAdminService;
	@Autowired
	private ZtAddrService ztAddrService;

	@Autowired
	private ZtOrderService ztOrderService;

	@Autowired
	private ZtGoodsService ztGoodsService;
	
	@Autowired
	private ZtJDorderService ztJDorderService;
	@Autowired
	private ZtTrolleyService ztTrolleyService;

	@Autowired
	private ZtColorService ztColorService;
	@Autowired
	private ZtSpecificationsService specificationsService;
	
	@Autowired
	ZtQuanService ztQuanService;

	@Autowired
	ZtGoodsOrderService ztGoodsOrderService;
	
	@Autowired  
    private MyProps myProps;

	@Autowired
	private DelayOrderService delayOrderService;

	/**
	 * 原生App支付 service 1微信 2 支付宝 3 h5微信 4 h5支付宝 5 微信扫码 6支付宝扫码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "wxPay")
	public void nativePay(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		Map<String, String> putMap = new HashMap<String, String>();

		String paramStr = getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		ZtOrder ztOrder = new ZtOrder();
	
		pay_title = "企购购商城";
		ResultObject res = new ResultObject();
		String totalPrice="0";
		openid = jo.getString("openid");
	
		if(jo.get("orderNo")!=null && StringUtils.isNotBlank(jo.get("orderNo").toString())){
			if(!"null".equals(orderNo)&&!"undefined".equals(orderNo)){
			
			orderNo = jo.get("orderNo").toString();
			ztOrder.setOrder(orderNo);
			ztOrder=ztOrderService.getByOrder(ztOrder);
			totalPrice=String.valueOf(ztOrder.getTotalPrice());
			}
		}else{
			orderNo = String.valueOf(UUID.next());
		

		String addr = jo.getString("addr").toString();
		String phone = jo.getString("phone").toString();
		String name = jo.getString("name").toString();
		
		String province = "";
		if(jo.get("province")!=null){
			province=jo.get("province").toString();
		}
		String city = "";
		if(jo.get("city")!=null){
			city=jo.get("city").toString();
		}
		String county = "";
		if(jo.get("county")!=null){
			county=jo.get("county").toString();
		}
		String town = "";
		if(jo.get("town")!=null){
			town=jo.get("town").toString();
		}
		int townbid = 0;
		if(jo.get("townbid")!=null){
			townbid=Integer.valueOf(jo.get("townbid").toString());
		}
		int citybid = 0;
		if(jo.get("citybid")!=null){
			citybid=Integer.valueOf(jo.get("citybid").toString());
		}
		int provincebid = 0;
		if(jo.get("provincebid")!=null){
			provincebid=Integer.valueOf(jo.get("provincebid").toString());
		}
		int countybid = 0;
		if(jo.get("countybid")!=null){
			countybid=Integer.valueOf(jo.get("countybid").toString());
		}
		String detailaddr = "";
		if(jo.get("detailaddr")!=null){
			detailaddr=jo.get("detailaddr").toString();
		}
		
		double freight = 0d;
		if(jo.get("freight")!=null){
			freight=Double.valueOf(jo.get("freight").toString());
		}
		
		
		 totalPrice = jo.get("totalPrice").toString();//  合计总价
		String goods = jo.get("goods").toString();// 商品或物品
		
		Double balance=0D;
		if(jo.get("balance")!=null){
			if(StringUtils.isNotBlank(jo.get("balance").toString())){
				balance = Double.valueOf(jo.get("balance").toString());
			}else{
				balance=0D;
			}
		}
		
		//更新购物车------------------START---------------
		if (StringUtils.isNotBlank(goods)) {
			
			JSONArray goodsArr = JSONArray.parseArray(goods);
			
			for (int i = 0; i < goodsArr.size(); i++) {
				JSONObject jno=goodsArr.getJSONObject(i);
				String trolleyid="";
				if(jno.get("trolleyid")!=null && StringUtils.isNotBlank(jno.get("trolleyid").toString())){
					trolleyid=jno.get("trolleyid").toString();
					ZtTrolley ztTrolley = new ZtTrolley();
					ztTrolley.setId(trolleyid);
					ztTrolleyService.delete(ztTrolley);
				}
			}
		}
		//更新购物车--------------------END---------------

		String adminid = jo.getString("adminid").toString();// 小程序用户id

		Date date = new Date();
		ztOrder.setAddr(addr);
		ztOrder.setPhone(phone);
		ztOrder.setFreight(freight);
		ztOrder.setName(name);
		ztOrder.setProvince(province);
		ztOrder.setDetailaddr(detailaddr);
		ztOrder.setCity(city);
		ztOrder.setCounty(county);
		ztOrder.setTown(town);
		ztOrder.setTownbid(townbid);
		ztOrder.setCitybid(citybid);
		ztOrder.setProvincebid(provincebid);
		ztOrder.setCountybid(countybid);
		ztOrder.setTotalPrice(Double.valueOf(totalPrice));//应付总额
		ztOrder.setBalance(balance);//余额抵扣
		ztOrder.setOrigPrice(Double.valueOf(totalPrice)+balance-freight);//商品总价
		ztOrder.setGoods(goods);
		ZtAdmin ztAdmin = new ZtAdmin();
		ztAdmin.setId(adminid);
		ztAdmin=ztAdminService.get(ztAdmin);
		
		if(ztAdmin==null || StringUtils.isBlank(ztAdmin.getId())){
			res.setResult(303L);
			res.setMsg("用户不存在");
			Render.renderString(response, res);
			return ;
		}
		
		ztOrder.setZtAdmin(ztAdmin);
		ztOrder.setCreateDate(date);
		ztOrder.setOrderTime(date);
		
		if(ztAdmin.getCashAmount()<balance){
			res.setResult(400L);
			res.setMsg("余额不足");
			Render.renderString(response, res);
			return ;
		}
		

		ztOrder.setOrderstatus("0");

		ztOrder.setOrder(orderNo);
		
		
			
			if(balance>0){
				ztAdmin.setAmount(ztAdmin.getAmount()+balance);//已使用的余额
				ztAdmin.setCashAmount(ztAdmin.getCashAmount()-balance);//可用余额
				ztAdminService.save(ztAdmin);
			}
			
			ztOrderService.save(ztOrder);
		
		}
		long dateTime = System.currentTimeMillis();

		Map<String, String> result = new HashMap<String, String>();
		putMap.put("pay_title", pay_title.trim());// 支付标题

		String spbill_create_ip = "";// getIpAddr_client
		try {

			spbill_create_ip = com.jeesite.modules.pay.totalPay.util.StringUtil
					.getIpAddr_client(request);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 控制器调用的时候填入，jar里面会自动填入微信
		putMap.put("total_fee",
				String.valueOf((int) (Double.valueOf(totalPrice) * 100)).trim());// 金额
		// 都是以分单位，支付宝传入的时候会自动变成分单位

		Map<String, String> nativePay = new HashMap<>();

		// 微信H5
		putMap.put("out_trade_no", orderNo.trim());
		putMap.put("openid", openid.trim());
		putMap.put("notify_url", ConstantUtil.NOTIFY_URL.trim());// 回调地址
		putMap.put("spbill_create_ip", spbill_create_ip.trim()); // 终端ip 微信支付需要
		// 支付宝不需要

		nativePay = NativePayService.weixinH5pay(putMap);
		nativePay.put("id", ztOrder.getId());

		res.setResult(200L);
		res.setData(nativePay);
		Render.renderString(response, res);

	}

	/**
	 * 微信异步回调
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "wx_notiyReturn")
	public String wx_notiyReturn(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		// 读取参数
		InputStream inputStream;
		int type = 0;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(
				inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		Map return_data = new HashMap();

		// 解析xml成map
		Map m = new HashMap();
		m = HttpXmlUtils.doXMLParse(sb.toString());

		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = (String) m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		String code = "";
		String msg = "";

		// 判断签名是否正确
		if (WxSignUtils.isWxPaySign("UTF-8", packageParams)) {
			// ------------------------------
			// 处理业务开始

			// ------------------------------
			String resXml = "";
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 支付成功
				Date da=new Date();
				String out_trade_no = (String) packageParams
						.get("out_trade_no");
				
				ZtOrder ztOrder = new ZtOrder();

				ztOrder.setOrder(out_trade_no);
				ztOrder = ztOrderService.getByOrder(ztOrder);
				if(ztOrder==null){
					return_data.put("return_code", "SUCCESS");
					return_data.put("return_msg", "OK");
					return HttpXmlUtils.GetMapToXML(return_data);
				}
				
				ZtAdmin ztAdmin=ztAdminService.get(ztOrder.getZtAdmin().getId());
				if(ztAdmin==null){
					return_data.put("return_code", "SUCCESS");
					return_data.put("return_msg", "OK");
					return HttpXmlUtils.GetMapToXML(return_data);
				}
				
				
				// 更新用户的付费状态和时间
				ztOrder.setPayTime(da);
			
				ztOrder.setOrderstatus("1");
				
				ztOrderService.save(ztOrder);//更新支付状态					
					
				ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
				ztGoodsOrder.setAddr(ztOrder.getAddr());
				ztGoodsOrder.setPhone(ztOrder.getPhone());
				ztGoodsOrder.setName(ztOrder.getName());

				ztGoodsOrder.setProvince(ztOrder.getProvince());
				ztGoodsOrder.setCity(ztOrder.getCity());
				ztGoodsOrder.setCounty(ztOrder.getCounty());
				ztGoodsOrder.setTown(ztOrder.getTown());
				ztGoodsOrder.setTownbid(ztOrder.getTownbid());
				ztGoodsOrder.setCitybid(ztOrder.getCitybid());
				ztGoodsOrder.setCountybid(ztOrder.getCountybid());
				ztGoodsOrder.setProvincebid(ztOrder.getProvincebid());
				ztGoodsOrder.setDetailaddr(ztOrder.getDetailaddr());
				ztGoodsOrder.setZtAdmin(ztOrder.getZtAdmin());

				ztGoodsOrder.setCreateDate(ztOrder.getCreateDate());
				ztGoodsOrder.setOrderTime(ztOrder.getOrderTime());

				ztGoodsOrder.setOrder(ztOrder.getOrder());
				ztGoodsOrder.setPayTime(ztOrder.getPayTime());
				
				
				JSONArray ja=new JSONArray();

				String goods = ztOrder.getGoods();

				double balance=ztOrder.getBalance();
				double freight=ztOrder.getFreight();
				
				
				
				if (StringUtils.isNotBlank(goods)) {
						
					JSONArray goodsArr = JSONArray.parseArray(goods);
					
					for (int i = 0; i < goodsArr.size(); i++) {
						String sku="";
						JSONObject jajb=new JSONObject();
						
						if(StringUtils.isNotBlank(ztGoodsOrder.getId())){
							ztGoodsOrder.setId("");
						}
							
						JSONObject jno=goodsArr.getJSONObject(i);
							
						ZtGoods ztGoods = ztGoodsService.get(jno.getString("goodsid"));
							
						
						//更新库存 ---------------------START---------------
						int count=Integer.valueOf(jno.get("numCount").toString());	
						String specificationsid="";
						if(jno.get("specificationsid")!=null&&StringUtils.isNotBlank(jno.get("specificationsid").toString())&&!"0".equals(jno.get("specificationsid").toString())){
							specificationsid=jno.get("specificationsid").toString();							
						}
						if(StringUtils.isNotBlank(specificationsid)&&!"0".equals(specificationsid)){
							ZtSpecifications ztSpecifications = new ZtSpecifications();
							ztSpecifications.setId(specificationsid);
							ztSpecifications=specificationsService.get(ztSpecifications);
							if(ztSpecifications!=null && StringUtils.isNotBlank(ztSpecifications.getId())){
							if(ztGoods.getSpotid()!=1){//不是京东
							ztSpecifications.setStock(ztSpecifications.getStock()-count);
							ztGoodsOrder.setSku(ztSpecifications.getSku());
							}else{
								sku=ztSpecifications.getSku();
								ztGoodsOrder.setSku(sku);
								if(StringUtils.isNotBlank(sku)){
								jajb.put("skuId",sku);
								jajb.put("num",count);
								jajb.put("bNeedAnnex",true);
								jajb.put("bNeedGift",false);
								ja.add(jajb);
								}
							}
							ztSpecifications.setSoldnum(ztSpecifications.getSoldnum()+count);
							specificationsService.save(ztSpecifications);
							
							
							
							}
						}
						String colorid=jno.getString("colorid");
						ZtColor ztColor = new ZtColor();
						ztColor.setId(colorid);
						ztColor = ztColorService.get(ztColor);
						
						if(StringUtils.isBlank(sku)){
							if(ztGoods.getSpotid()==1){//是京东
								
							sku=ztColor.getSku();
							ztGoodsOrder.setSku(sku);
							if(StringUtils.isNotBlank(sku)){
							jajb.put("skuId",sku);
							jajb.put("num",count);
							jajb.put("bNeedAnnex",true);
							jajb.put("bNeedGift",false);
							ja.add(jajb);
							}
							
							}else{
								ztGoodsOrder.setSku(ztColor.getSku());
							}
						}
						
							
							if(ztGoods.getSpotid()!=1){
							ztColor.setNumCount(ztColor.getNumCount()
									- count);//库存
							}
							ztColor.setSoldCount(ztColor.getSoldCount()+count);//已销售数量
							
							ztColorService.saveByOrder(ztColor);// 更新库存
							
							ztGoods.setSoldCount(ztGoods.getSoldCount()+count);
							if(ztGoods.getSpotid()!=1){
								ztGoods.setCount(ztGoods.getCount()-count);
							}
							ztGoodsService.save(ztGoods);
							
							double price=Double.valueOf(jno.get("price").toString());//商品小计
							ztGoodsOrder.setNumCount(count);// 数量
						
							ztGoodsOrder.setZtGoods(ztGoods);//商品id
							
							ztGoodsOrder.setSpotid(ztGoods.getSpotid());
							if(ztGoods.getSpotid()!=1){
							ztGoodsOrder.setOrderstatus(ztOrder.getOrderstatus());
							}else{
								ztGoodsOrder.setOrderstatus("1");
							}
							ztGoodsOrder.setColorid(colorid);
							ztGoodsOrder.setSpecificationsid(specificationsid);
							if(i==0){
							ztGoodsOrder.setFreight(Double.valueOf(freight));//运费
							}else{
								ztGoodsOrder.setFreight(0d);
							}
							ztGoodsOrder.setGoodsPrice(Double.valueOf(jno.get("goodsPrice").toString()));//商品单价
							Double p=price+ztGoodsOrder.getFreight();

							if(balance<=p){
							ztGoodsOrder.setBalance(balance);
							ztGoodsOrder.setTotalPrice(p-balance);
							}else{
								ztGoodsOrder.setBalance(p);
								ztGoodsOrder.setTotalPrice(0D);
								balance=balance-p;
							}
							
							ztGoodsOrderService.save(ztGoodsOrder);
							
							forBalance(ztGoodsOrder);
						//	forFinancial(ztGoods,ztAdmin,da,count);
							
						}
					
					if(ja!=null && ja.size()>0){
						orderUniteSubmit(ja, ztOrder.getOrder(),ztOrder.getName(), ztOrder.getProvincebid(), ztOrder.getCitybid(), ztOrder.getCountybid(), ztOrder.getTownbid(), ztOrder.getAddr(), ztOrder.getPhone());
					}

					}
					
				return_data.put("return_code", "SUCCESS");
				return_data.put("return_msg", "OK");

			} else {

				return_data.put("return_code", "FAIL");
				return_data.put("return_msg", "签名错误");
			}

		} else {

		}

		return HttpXmlUtils.GetMapToXML(return_data);

	}

	
	
	@ResponseBody
	@RequestMapping(value = "resultSuc")
	public void resultSuc(HttpServletRequest request,
			HttpServletResponse response) {

		JSONObject obj = new JSONObject();

		String zf = null;
		try {

			String outTNo = request.getParameter("outTNo");

			zf = (String) CacheUtils.get(outTNo + "WXZF");

			if (StringUtils.isNotBlank(zf)) {

				obj.put("result", "ok");

				CacheUtils.put(outTNo + "WXZF", "");
				CacheUtils.remove(outTNo + "WXZF");

			} else {

				obj.put("result", "fail");
			}

			response.getWriter().print(obj.toString());

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	public String getParams(HttpServletRequest request) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream()));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			String appMsg = sb.toString();
			return appMsg;
		} catch (Exception ex) {
			ex.printStackTrace();

		}
		return "";
	}
	
	/**
	 * 应付0元
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "forOrder")
	public void forOrder(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ResultObject res = new ResultObject();
		String paramStr = getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		ZtOrder ztOrder = new ZtOrder();
		pay_title = "企购购商城";
		
		openid = jo.getString("openid");
		boolean isOrderTemp=false;
		if(jo.get("orderNo")!=null){
			if(!"null".equals(orderNo)&&!"undefined".equals(orderNo)){
			isOrderTemp=true;
			orderNo = jo.get("orderNo").toString();
			}
		}else{
			orderNo = String.valueOf(UUID.next());
		}

		String addr = jo.getString("addr").toString();
		String phone = jo.getString("phone").toString();
		String name = jo.getString("name").toString();
		String province = "";
		if(jo.get("province")!=null){
			province=jo.get("province").toString();
		}
		String city = "";
		if(jo.get("city")!=null){
			city=jo.get("city").toString();
		}
		String county = "";
		if(jo.get("county")!=null){
			county=jo.get("county").toString();
		}
		
		String town = "";
		if(jo.get("town")!=null){
			town=jo.get("town").toString();
		}
		int townbid = 0;
		if(jo.get("townbid")!=null){
			townbid=Integer.valueOf(jo.get("townbid").toString());
		}
		int citybid = 0;
		if(jo.get("citybid")!=null){
			citybid=Integer.valueOf(jo.get("citybid").toString());
		}
		int provincebid = 0;
		if(jo.get("provincebid")!=null){
			provincebid=Integer.valueOf(jo.get("provincebid").toString());
		}
		int countybid = 0;
		if(jo.get("countybid")!=null){
			countybid=Integer.valueOf(jo.get("countybid").toString());
		}
		
		String detailaddr = "";
		if(jo.get("detailaddr")!=null){
			detailaddr=jo.get("detailaddr").toString();
		}
		
		String totalPrice = jo.getString("totalPrice").toString();//  合计总价
		if(Double.valueOf(totalPrice)==0D){
		Double balance=0D;
		if(jo.get("balance")!=null){
			if(StringUtils.isNotBlank(jo.get("balance").toString())){
				balance = Double.valueOf(jo.get("balance").toString());
			}else{
				balance=0D;
			}
		}
		
		
		String goods = jo.getString("goods").toString();// 商品或物品

		String adminid = jo.getString("adminid").toString();// 小程序用户id
		
		double freight = 0d;
		if(jo.get("freight")!=null){
			freight=Double.valueOf(jo.get("freight").toString());
		}

		Date date = new Date();
		ztOrder.setAddr(addr);
		ztOrder.setPhone(phone);
		ztOrder.setName(name);
		ztOrder.setProvince(province);
		ztOrder.setCity(city);
		ztOrder.setCounty(county);
		ztOrder.setTown(town);
		ztOrder.setTownbid(townbid);
		ztOrder.setCitybid(citybid);
		ztOrder.setCountybid(countybid);
		ztOrder.setProvincebid(provincebid);
		ztOrder.setTotalPrice(Double.valueOf(totalPrice));//应付总价
		ztOrder.setBalance(balance);//余额
		ztOrder.setOrigPrice(Double.valueOf(totalPrice)+balance-freight);//商品总价
		ztOrder.setGoods(goods);
		ZtAdmin ztAdmin = new ZtAdmin();
		ztAdmin.setId(adminid);
		ztAdmin=ztAdminService.get(ztAdmin);
		ztOrder.setZtAdmin(ztAdmin);
		ztOrder.setCreateDate(date);
		ztOrder.setOrderTime(date);
		ztOrder.setPayTime(date);
		ztOrder.setOrderstatus("1");
		ztOrder.setOrder(orderNo);
		
		if(ztAdmin==null || StringUtils.isBlank(ztAdmin.getId())){
			res.setResult(303L);
			res.setMsg("用户不存在");
			Render.renderString(response, res);
			return ;
		}
		if(ztAdmin.getCashAmount()<balance){
			res.setResult(400L);
			res.setMsg("余额不足");
			Render.renderString(response, res);
			return ;
		}
		if (!StringUtils.isNotBlank(goods)) {
			res.setResult(300L);
			res.setMsg("商品信息有误！");
			Render.renderString(response, res);
			return;
		}
		
		if(balance>0){
			ztAdmin.setAmount(ztAdmin.getAmount()+balance);//已使用的余额
			ztAdmin.setCashAmount(ztAdmin.getCashAmount()-balance);
			ztAdminService.save(ztAdmin);
		}
		
		ztOrder.setFreight(freight);
		ztOrder.setDetailaddr(detailaddr);
		if(!isOrderTemp){
		ztOrderService.save(ztOrder);
		}
		
		
			ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
			ztGoodsOrder.setAddr(ztOrder.getAddr());
			ztGoodsOrder.setPhone(ztOrder.getPhone());
			ztGoodsOrder.setName(ztOrder.getName());
			
			ztGoodsOrder.setProvince(ztOrder.getProvince());
			ztGoodsOrder.setCity(ztOrder.getCity());
			ztGoodsOrder.setCounty(ztOrder.getCounty());
			ztGoodsOrder.setTown(ztOrder.getTown());
			ztGoodsOrder.setTownbid(ztOrder.getTownbid());
			ztGoodsOrder.setCitybid(ztOrder.getCitybid());
			ztGoodsOrder.setCountybid(ztOrder.getCountybid());
			ztGoodsOrder.setProvincebid(ztOrder.getProvincebid());
			ztGoodsOrder.setDetailaddr(detailaddr);
			ztGoodsOrder.setZtAdmin(ztOrder.getZtAdmin());

			ztGoodsOrder.setCreateDate(ztOrder.getCreateDate());
			ztGoodsOrder.setOrderTime(ztOrder.getOrderTime());

			ztGoodsOrder.setOrder(ztOrder.getOrder());
			ztGoodsOrder.setPayTime(ztOrder.getPayTime());
			
			JSONArray ja=new JSONArray();
			
			
			

			JSONArray goodsArr = JSONArray.parseArray(goods);
			for (int i = 0; i < goodsArr.size(); i++) {
				if(StringUtils.isNotBlank(ztGoodsOrder.getId())){
					ztGoodsOrder.setId("");
				}
				JSONObject jajb=new JSONObject();
				String sku="";

				JSONObject jno=goodsArr.getJSONObject(i);

				ZtGoods ztGoods = ztGoodsService.get(jno.getString("goodsid"));

				//更新库存 ---------------------START---------------
				int count=Integer.valueOf(jno.get("numCount").toString());
				String specificationsid="";
				if(jno.get("specificationsid")!=null && StringUtils.isNotBlank(jno.get("specificationsid").toString())&&!"0".equals(jno.get("specificationsid").toString())){
					specificationsid=jno.get("specificationsid").toString();

				}
				if(StringUtils.isNotBlank(specificationsid)&&!"0".equals(specificationsid)){
					ZtSpecifications ztSpecifications = new ZtSpecifications();
					ztSpecifications.setId(specificationsid);
					ztSpecifications=specificationsService.get(ztSpecifications);
					if(ztSpecifications!=null){
						if(ztGoods.getSpotid()!=1){
							ztSpecifications.setStock(ztSpecifications.getStock()-count);
						}
						ztSpecifications.setSoldnum(ztSpecifications.getSoldnum()+count);
						specificationsService.save(ztSpecifications);



						if(ztGoods.getSpotid()!=1){//不是京东
							ztSpecifications.setStock(ztSpecifications.getStock()-count);
							ztGoodsOrder.setSku(ztSpecifications.getSku());
						}else{
							sku=ztSpecifications.getSku();
							ztGoodsOrder.setSku(sku);
							if(StringUtils.isNotBlank(sku)){
								jajb.put("skuId",sku);
								jajb.put("num",count);
								jajb.put("bNeedAnnex",true);
								jajb.put("bNeedGift",false);
								ja.add(jajb);
							}
						}


					}
				}
				String colorid=jno.getString("colorid");
				ZtColor ztColor = new ZtColor();
				ztColor.setId(colorid);
				ztColor = ztColorService.get(ztColor);

				if(StringUtils.isBlank(sku)){
					if(ztGoods.getSpotid()==1){//是京东

						sku=ztColor.getSku();
						ztGoodsOrder.setSku(sku);
						if(StringUtils.isNotBlank(sku)){
							jajb.put("skuId",sku);
							jajb.put("num",count);
							jajb.put("bNeedAnnex",true);
							jajb.put("bNeedGift",false);
							ja.add(jajb);
						}

					}else{
						ztGoodsOrder.setSku(ztColor.getSku());
					}
				}

				if(ztGoods.getSpotid()!=1){
					ztColor.setNumCount(ztColor.getNumCount()
							- count);//库存
				}

				ztColor.setSoldCount(ztColor.getSoldCount()+count);//已销售数量

				ztColorService.saveByOrder(ztColor);// 更新库存

				ztGoods.setSoldCount(ztGoods.getSoldCount()+count);
				if(ztGoods.getSpotid()!=1){
					ztGoods.setCount(ztGoods.getCount()-count);
				}
				ztGoodsService.save(ztGoods);
				//更新库存 ---------------------END---------------

				//更新购物车------------------START---------------
				String trolleyid="";
				if(jno.get("trolleyid")!=null && StringUtils.isNotBlank(jno.get("trolleyid").toString())){
					trolleyid=jno.get("trolleyid").toString();
					ZtTrolley ztTrolley = new ZtTrolley();
					ztTrolley.setId(trolleyid);
					ztTrolleyService.delete(ztTrolley);
				}

				double price=Double.valueOf(jno.get("price").toString());//商品小计
				ztGoodsOrder.setNumCount(count);// 数量

				ztGoodsOrder.setZtGoods(ztGoods);//商品id
				ztGoodsOrder.setSpotid(ztGoods.getSpotid());
				if(ztGoods.getSpotid()!=1){//不是京东渠道的订单
					ztGoodsOrder.setOrderstatus(ztOrder.getOrderstatus());
				}else{
					ztGoodsOrder.setOrderstatus("1");
				}
				ztGoodsOrder.setColorid(colorid);
				ztGoodsOrder.setSpecificationsid(specificationsid);
				if(i==0){
					ztGoodsOrder.setFreight(Double.valueOf(freight));//运费
				}else{
					ztGoodsOrder.setFreight(0d);
				}

				ztGoodsOrder.setGoodsPrice(Double.valueOf(jno.get("goodsPrice").toString()));//商品单价

				Double p=price+ztGoodsOrder.getFreight();
				if(balance<=p){
					ztGoodsOrder.setBalance(balance);
					ztGoodsOrder.setTotalPrice(0D);
				}else{
					ztGoodsOrder.setBalance(p);
					ztGoodsOrder.setTotalPrice(0D);
					balance=balance-p;
				}


				ztGoodsOrderService.save(ztGoodsOrder);
				forBalance(ztGoodsOrder);
				//	forFinancial(ztGoods,ztAdmin,date,count);
			}

			if(ja!=null && ja.size()>0){
				orderUniteSubmit(ja,ztOrder.getOrder(), name, provincebid, citybid, countybid, townbid, addr, phone);
			}

		}
		res.setData(ztOrder);
		res.setResult(200L);
		Render.renderString(response, res);

	}
	/**
	 * 明细  支出
	 * @param ztGoodsOrder

	 */
	public void forBalance(ZtGoodsOrder ztGoodsOrder){
		double balance=ztGoodsOrder.getBalance();
		double total = ztGoodsOrder.getTotalPrice();
		List<ZtFinancial> list = new ArrayList<>();

		if(balance>0D){

			ZtFinancial ztFinancial=new ZtFinancial();
			ztFinancial.setAudit("2");
			ztFinancial.setType("3");
			ztFinancial.setContent("积分支付-"+ztGoodsOrder.getZtGoods().getTitle());
			ztFinancial.setZtAdmin(ztGoodsOrder.getZtAdmin());
			ztFinancial.setPricestr("-￥"+String.format("%.2f",balance));
			ztFinancial.setPrice(balance);
			ztFinancial.setCreateDate(new Date());
			ztFinancial.setUsername(ztGoodsOrder.getZtAdmin().getUsername());
			ztFinancial.setHeadimgurl(ztGoodsOrder.getZtAdmin().getHeadimgurl());
			ztFinancial.setPhone(ztGoodsOrder.getZtAdmin().getPhone());
			ztFinancial.setZtGoods(ztGoodsOrder.getZtGoods());
			ztFinancial.setStatus("0");
			ztFinancial.setOperation("系统");
			list.add(ztFinancial);
		}
		if(total>0D){

			ZtFinancial ztFinancial=new ZtFinancial();
			ztFinancial.setAudit("2");
			ztFinancial.setType("3");
			ztFinancial.setContent("微信支付-"+ztGoodsOrder.getZtGoods().getTitle());
			ztFinancial.setZtAdmin(ztGoodsOrder.getZtAdmin());
			ztFinancial.setPricestr("-￥"+String.format("%.2f",total));
			ztFinancial.setPrice(total);
			ztFinancial.setCreateDate(new Date());
			ztFinancial.setUsername(ztGoodsOrder.getZtAdmin().getUsername());
			ztFinancial.setHeadimgurl(ztGoodsOrder.getZtAdmin().getHeadimgurl());
			ztFinancial.setPhone(ztGoodsOrder.getZtAdmin().getPhone());
			ztFinancial.setZtGoods(ztGoodsOrder.getZtGoods());
			ztFinancial.setStatus("0");
			ztFinancial.setOperation("系统");
			list.add(ztFinancial);
		}
		if(list.size()>0){
			ztFinancialService.insertBatch(list);
		}
	}
	
	public void forFinancial(ZtGoods ztGoods,ZtAdmin ztAdmin,Date da,int numCount){
		
		String lastadminid=ztAdmin.getLastadmin();
		
		if(StringUtils.isNotBlank(lastadminid)){//有上级
			/**一级返佣******START********/
			ZtAdmin lastadmin=new ZtAdmin();
			lastadmin.setId(lastadminid);
			lastadmin=ztAdminService.get(lastadmin);
			String level=lastadmin.getLevel();
			double priceGoods=0D;
			String adminLevel=ztAdmin.getLevel();
			if("0".equals(level)){
				priceGoods=ztGoods.getCommonOnePrice();
			}else if("1".equals(level)){
				
				if("0".equals(adminLevel)){
					priceGoods=ztGoods.getCopperOnePrice();
				}else if("1".equals(adminLevel)){
					priceGoods=ztGoods.getTcopperOnePrice();
				}else if("2".equals(adminLevel)){
					priceGoods=ztGoods.getYcopperOnePrice();
				}else if("3".equals(adminLevel)){
					priceGoods=ztGoods.getJcopperOnePrice();
				}
				
			}else if("2".equals(level)){
				
				if("0".equals(adminLevel)){
					priceGoods=ztGoods.getSilverOnePrice();
				}else if("1".equals(adminLevel)){
					priceGoods=ztGoods.getTsilverOnePrice();
				}else if("2".equals(adminLevel)){
					priceGoods=ztGoods.getYsilverOnePrice();
				}else if("3".equals(adminLevel)){
					priceGoods=ztGoods.getJsilverOnePrice();
				}
				
			}else if("3".equals(level)){
			
				if("0".equals(adminLevel)){
					priceGoods=ztGoods.getGoldOnePrice();
				}else if("1".equals(adminLevel)){
					priceGoods=ztGoods.getTgoldOnePrice();
				}else if("2".equals(adminLevel)){
					priceGoods=ztGoods.getYgoldOnePrice();
				}else if("3".equals(adminLevel)){
					priceGoods=ztGoods.getJgoldOnePrice();
				}
			}
			
			 BigDecimal b1 = new BigDecimal(priceGoods);
             BigDecimal b2 = new BigDecimal(numCount);
            
	         String dff= new java.text.DecimalFormat("#.00").format(b1.multiply(b2).doubleValue());
	             
	          priceGoods=  Double.valueOf(dff);
			if(priceGoods!=0d){
				lastadmin.setAmount((lastadmin.getAmount()==null?0:lastadmin.getAmount())+priceGoods);
				//lastadmin.setCashAmount((lastadmin.getCashAmount()==null?0:lastadmin.getCashAmount())+priceGoods);
				ztAdminService.save(lastadmin);
			
			
			ZtFinancial ztFinancial=new ZtFinancial();
			ztFinancial.setType("1");
			ztFinancial.setContent("(待入)商品订单-"+ztGoods.getTitle());
			ztFinancial.setZtAdmin(lastadmin);
			ztFinancial.setZtGoods(ztGoods);
			ztFinancial.setPricestr("￥"+priceGoods);
			ztFinancial.setPrice(priceGoods);
			ztFinancial.setCreateDate(da);
			ztFinancial.setUsername("(粉丝)"+ztAdmin.getUsername());
			ztFinancial.setHeadimgurl(ztAdmin.getHeadimgurl());
			ztAdminService.setNames();
			ztFinancialService.save(ztFinancial);
			}
			/**一级返佣******END********/
			
			String lastTwoadminid=lastadmin.getLastadmin();
			if(StringUtils.isNotBlank(lastTwoadminid)){//有上级
				/**二级返佣******START********/
				ZtAdmin lastTwoadmin=new ZtAdmin();
				lastTwoadmin.setId(lastTwoadminid);
				lastTwoadmin=ztAdminService.get(lastTwoadmin);
				 level=lastTwoadmin.getLevel();
				 priceGoods=0D;
				if("0".equals(level)){
					
				}else if("1".equals(level)){
					if("0".equals(adminLevel)){
						priceGoods=ztGoods.getCopperTwoPrice();
					}else if("1".equals(adminLevel)){
						priceGoods=ztGoods.getTcopperTwoPrice();
					}else if("2".equals(adminLevel)){
						priceGoods=ztGoods.getYcopperTwoPrice();
					}else if("3".equals(adminLevel)){
						priceGoods=ztGoods.getJcopperTwoPrice();
					}
					
				}else if("2".equals(level)){
					
					
					if("0".equals(adminLevel)){
						priceGoods=ztGoods.getSilverTwoPrice();
					}else if("1".equals(adminLevel)){
						priceGoods=ztGoods.getTsilverTwoPrice();
					}else if("2".equals(adminLevel)){
						priceGoods=ztGoods.getYsilverTwoPrice();
					}else if("3".equals(adminLevel)){
						priceGoods=ztGoods.getJsilverTwoPrice();
					}
					
				}else if("3".equals(level)){
				
					if("0".equals(adminLevel)){
						priceGoods=ztGoods.getGoldTwoPrice();
					}else if("1".equals(adminLevel)){
						priceGoods=ztGoods.getTgoldTwoPrice();
					}else if("2".equals(adminLevel)){
						priceGoods=ztGoods.getYgoldTwoPrice();
					}else if("3".equals(adminLevel)){
						priceGoods=ztGoods.getJgoldTwoPrice();
					}
					
				}
				if(priceGoods!=0d){
				lastTwoadmin.setAmount((lastTwoadmin.getAmount()==null?0:lastTwoadmin.getAmount())+priceGoods);
				//lastTwoadmin.setCashAmount((lastTwoadmin.getCashAmount()==null?0:lastTwoadmin.getCashAmount())+priceGoods);
				ztAdminService.save(lastTwoadmin);
				
				ZtFinancial ztFinancial2=new ZtFinancial();
				ztFinancial2.setType("2");
				ztFinancial2.setContent("(待入)商品订单-"+ztGoods.getTitle());
				ztFinancial2.setZtAdmin(lastTwoadmin);
				ztFinancial2.setPricestr("￥"+priceGoods);
				ztFinancial2.setPrice(priceGoods);
				ztFinancial2.setZtGoods(ztGoods);
				ztFinancial2.setCreateDate(da);
				ztFinancial2.setUsername(lastadmin.getUsername());
				ztFinancial2.setHeadimgurl(lastadmin.getHeadimgurl());
				ztAdminService.setNames();
				ztFinancialService.save(ztFinancial2);
				}
				/**二级返佣******END********/
			}
			
		}
	}
	
	/**
	 * 同步渠道（京东）下单
	 * @param ja
	 * @param order
	 * @param name
	 * @param provincebid
	 * @param citybid
	 * @param countybid
	 * @param townbid
	 * @param addr
	 * @param phone
	 */
	public void orderUniteSubmit(JSONArray ja,String order,String name,
			int provincebid,int citybid,int countybid,int townbid,String addr,String phone){
		JSONObject orderinfoJo=new JSONObject();
		orderinfoJo.put("sku", ja);
		orderinfoJo.put("thirdOrder",order);
		orderinfoJo.put("name", name);
		orderinfoJo.put("province", provincebid);
		orderinfoJo.put("city", citybid);
		orderinfoJo.put("county", countybid);
		orderinfoJo.put("town", townbid);
		orderinfoJo.put("address", addr);
		orderinfoJo.put("mobile", phone);
		orderinfoJo.put("email", "1714850193@qq.com");//邮箱
		orderinfoJo.put("invoiceState", 2);
		orderinfoJo.put("invoiceType", 1);//1普通发票    2增值税发票
		orderinfoJo.put("selectedInvoiceTitle", 5);
		orderinfoJo.put("companyName", "广州领互科技有限公司");//发票抬头
		orderinfoJo.put("invoiceContent", 1);
		orderinfoJo.put("paymentType", 4);
		orderinfoJo.put("isUseBalance", 1);
		orderinfoJo.put("submitState", 0);

		DelayOrder delayOrder = new DelayOrder();
		delayOrder.setContent(orderinfoJo.toJSONString());
		delayOrder.setOrder(order);
		delayOrder.setStatus("0");
		delayOrder.setExpireTime(DateUtils.getDateHour(new Date(),1));
		delayOrderService.save(delayOrder);

		
	/*	JSONObject resultJO=ProductPoolUtils.orderUniteSubmit(orderinfoJo.toJSONString());
	//	System.out.println("liukun----"+resultJO.toString());
		if(resultJO!=null){
		String jdOrderId=resultJO.get("jdOrderId").toString();
		double orderPrice=resultJO.getDouble("orderPrice");
		double freight=resultJO.getDouble("freight");
		JSONArray jna=resultJO.getJSONArray("sku");
		
		
		List<ZtGoodsOrder> ztGoodsOrderList=new ArrayList<ZtGoodsOrder>();
		
		if(jna!=null && jna.size()>0){
		for(int i=0;i<jna.size();i++){
			
			JSONObject jct=jna.getJSONObject(i);
			double p=jct.getDouble("price");
			String sku=jct.get("skuId").toString();
			*//*String goodsTitle=jct.get("name").toString();
			int num=jct.getInteger("num");*//*
			
			ZtGoodsOrder ztGoodsOrder=new ZtGoodsOrder();
			ztGoodsOrder.setOrder(order);
			ztGoodsOrder.setChannelorder(jdOrderId);
			ztGoodsOrder.setSku(sku);
			ztGoodsOrder.setChannelprice(p);
			ztGoodsOrder.setOrder(order);
			ztGoodsOrderList.add(ztGoodsOrder);
			
		}
		//
		ztGoodsOrderService.batchUpdateChannel(ztGoodsOrderList);
		
		}
		boolean isOccupyStock=ProductPoolUtils.occupyStock(jdOrderId);//确认订单
		
		if(isOccupyStock){
			Date da=new Date();
			ZtJDorder ztJDorder=new ZtJDorder();
			ztJDorder.setOrder(order);
			ztJDorder.setFreight(freight);
			ztJDorder.setGoods(jna.toString());
			ztJDorder.setCreateDate(da);
			ztJDorder.setPayTime(da);
			ztJDorder.setJdorderid(jdOrderId);
			ztJDorderService.save(ztJDorder);
		}
		
		}*/
	}


}
